const db = require('../db/index')

const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config')




exports.login = function(req, res) {
    let { username, password } = req.body
    const sql = 'select * from ev_users where username=?'
    db.query(sql, username, (err, rows) => {
        if (err) {
            return res.cc(err)
        }
        if (rows.length !== 1) {
            return res.cc('用户不存在')
        }
        const flag = bcrypt.compareSync(password, rows[0].password)
        if (!flag) {
            return res.cc('用户不存在或密码错误')
        }
        const user = {
            ...rows[0],
            password: '',
            user_pic: '',
        }

        const token = 'Bearer ' + jwt.sign(user, config.jwtKey, { expiresIn: '10h' })
        console.log(token);
        res.send({
            status: 0,
            message: '用户登录成功',
            token,
        })
    })

}



exports.regUser = function(req, res) {
    console.log(req.body);
    const userinfo = req.body

    const sql = "select * from ev_users where username=?"

    db.query(sql, userinfo.username, (err, results) => {
        if (err) {
            // return res.send({
            //     status: 1,
            //     message: err.message,
            // })
            return res.cc(err)
        }
        if (results.length !== 0) {
            // return res.send({
            //     status: 1,
            //     message: '用户已经存在',
            // })
            return res.cc('用户已经存在')
        } else {
            userinfo.password = bcrypt.hashSync(userinfo.password, 10)
            console.log(userinfo);

            const sqlInsert = 'insert into ev_users set ?'
            db.query(sqlInsert, userinfo, function(err, result) {
                if (err) {
                    // return res.send({
                    //     status: 1,
                    //     message: err.message,
                    // })
                    return res.cc(err)
                }

                if (result.affectedRows == 1) {
                    // res.send({
                    //     status: 0,
                    //     message: '用户注册成功！first',
                    // })
                    res.cc('用户注册成功！first', 0)
                } else {
                    // result.send({
                    //     status: 1,
                    //     message: "insert failed",
                    // })
                    res.cc('insert failed')
                }
            })
        }
    })

}